package com.offlineanswer;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.offlineanswer.databinding.ActivityMainBinding;
import com.offlineanswer.databinding.DialogInputBinding;
import com.offlineanswer.databinding.FloatAnswersBinding;
import com.offlineanswer.databinding.FloatBigBinding;
import com.offlineanswer.databinding.FloatQueryBinding;
import com.offlineanswer.databinding.FloatSmallBinding;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@SuppressLint("ClickableViewAccessibility")
@RequiresApi(api = Build.VERSION_CODES.M)
public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private FloatBigBinding bigBinding;
    private FloatSmallBinding smallBinding;
    private WindowManager.LayoutParams layoutParams;
    private WindowManager windowManager;
    private float firstX,firstY;
    private int lpX,lpY;
    private FloatAnswersBinding floatAnswers;
    private AnswerAdapter answeradp;
    private final List<String> answerdata=new ArrayList<>();
    private FloatQueryBinding queryBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        initLayout();
        initListener();
        initBigListener();
        initSmallListener();
        initAnswers();
        initQuery();
    }
    private void initQuery() {
        queryBinding.queryClose.setOnClickListener(view -> {
            windowManager.removeView(queryBinding.getRoot());
            windowManager.addView(bigBinding.getRoot(),layoutParams);
        });
        queryBinding.queryTab.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction()==MotionEvent.ACTION_DOWN){
                firstX=motionEvent.getRawX();
                firstY=motionEvent.getRawY();
                lpX=layoutParams.x;
                lpY=layoutParams.y;
            }else if (motionEvent.getAction()==MotionEvent.ACTION_MOVE){
                layoutParams.x= (int) (lpX+(motionEvent.getRawX()-firstX));
                layoutParams.y= (int) (lpY+(motionEvent.getRawY()-firstY));
                windowManager.updateViewLayout(queryBinding.getRoot(),layoutParams);
            }
            return true;
        });
        queryBinding.queryBottom.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction()==MotionEvent.ACTION_DOWN){
                firstX=motionEvent.getRawX();
                firstY=motionEvent.getRawY();
                lpX=layoutParams.x;
                lpY=layoutParams.y;
            }else if (motionEvent.getAction()==MotionEvent.ACTION_MOVE){
                layoutParams.x= (int) (lpX+(motionEvent.getRawX()-firstX));
                layoutParams.y= (int) (lpY+(motionEvent.getRawY()-firstY));
                windowManager.updateViewLayout(floatAnswers.getRoot(),layoutParams);
            }
            return true;
        });
        queryBinding.query1.setOnClickListener(view -> {
            @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
            edit.putBoolean("query1",queryBinding.query1.isChecked());
            edit.apply();
        });
        queryBinding.query2.setOnClickListener(view -> {
            @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
            edit.putBoolean("query2",queryBinding.query2.isChecked());
            edit.apply();
        });
        queryBinding.query3.setOnClickListener(view -> {
            @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
            edit.putBoolean("query3",queryBinding.query3.isChecked());
            edit.apply();
        });
        queryBinding.query4.setOnClickListener(view -> {
            @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
            edit.putBoolean("query4",queryBinding.query4.isChecked());
            edit.apply();
        });
        queryBinding.query5.setOnClickListener(view -> {
            @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
            edit.putBoolean("query5",queryBinding.query5.isChecked());
            edit.apply();
        });

        queryBinding.query1.setChecked(App.sp.getBoolean("query1",true));
        queryBinding.query2.setChecked(App.sp.getBoolean("query2",false));
        queryBinding.query3.setChecked(App.sp.getBoolean("query3",false));
        queryBinding.query4.setChecked(App.sp.getBoolean("query4",false));
        queryBinding.query5.setChecked(App.sp.getBoolean("query5",false));
    }

    private void initAnswers() {
        floatAnswers.answersTab.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction()==MotionEvent.ACTION_DOWN){
                firstX=motionEvent.getRawX();
                firstY=motionEvent.getRawY();
                lpX=layoutParams.x;
                lpY=layoutParams.y;
            }else if (motionEvent.getAction()==MotionEvent.ACTION_MOVE){
                layoutParams.x= (int) (lpX+(motionEvent.getRawX()-firstX));
                layoutParams.y= (int) (lpY+(motionEvent.getRawY()-firstY));
                windowManager.updateViewLayout(floatAnswers.getRoot(),layoutParams);
            }
            return true;
        });
        floatAnswers.answersBottom.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction()==MotionEvent.ACTION_DOWN){
                firstX=motionEvent.getRawX();
                firstY=motionEvent.getRawY();
                lpX=layoutParams.x;
                lpY=layoutParams.y;
            }else if (motionEvent.getAction()==MotionEvent.ACTION_MOVE){
                layoutParams.x= (int) (lpX+(motionEvent.getRawX()-firstX));
                layoutParams.y= (int) (lpY+(motionEvent.getRawY()-firstY));
                windowManager.updateViewLayout(floatAnswers.getRoot(),layoutParams);
            }
            return true;
        });
        floatAnswers.answersBack.setOnClickListener(view -> {
            windowManager.removeView(floatAnswers.getRoot());
            setFloatPara(0);
            windowManager.addView(bigBinding.getRoot(),layoutParams);
        });
        answeradp=new AnswerAdapter(this,answerdata);
        floatAnswers.answerList.setAdapter(answeradp);
        floatAnswers.answerList.setOnItemClickListener((adapterView, view, i, l) -> {
            if (MyAccessibility.mService!=null) MyAccessibility.mService.inputText(answerdata.get(i));
            windowManager.removeView(floatAnswers.getRoot());
            setFloatPara(0);
            windowManager.addView(bigBinding.getRoot(),layoutParams);
        });
    }
    private void initSmallListener() {
        smallBinding.smallButton.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction()==MotionEvent.ACTION_DOWN){
                firstX=motionEvent.getRawX();
                firstY=motionEvent.getRawY();
                lpX=layoutParams.x;
                lpY=layoutParams.y;
            }else if (motionEvent.getAction()==MotionEvent.ACTION_MOVE){
                layoutParams.x= (int) (lpX+(motionEvent.getRawX()-firstX));
                layoutParams.y= (int) (lpY+(motionEvent.getRawY()-firstY));
                windowManager.updateViewLayout(smallBinding.getRoot(),layoutParams);
            }
            return false;
        });
        smallBinding.smallButton.setOnClickListener(view -> {
            windowManager.removeView(smallBinding.getRoot());
            setFloatPara(0);
            windowManager.addView(bigBinding.getRoot(), layoutParams);
            bigBinding.openService.setChecked(MyAccessibility.isStart());
        });
    }
    private void initBigListener() {
        bigBinding.bigClose.setOnClickListener(view -> windowManager.removeView(bigBinding.getRoot()));
        bigBinding.bigToSmall.setOnClickListener(view -> {
            windowManager.removeView(bigBinding.getRoot());
            setFloatPara(1);
            windowManager.addView(smallBinding.getRoot(),layoutParams);
        });
        bigBinding.bigTab.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction()==MotionEvent.ACTION_DOWN){
                firstX=motionEvent.getRawX();
                firstY=motionEvent.getRawY();
                lpX=layoutParams.x;
                lpY=layoutParams.y;
            }else if (motionEvent.getAction()==MotionEvent.ACTION_MOVE){
                layoutParams.x= (int) (lpX+(motionEvent.getRawX()-firstX));
                layoutParams.y= (int) (lpY+(motionEvent.getRawY()-firstY));
                windowManager.updateViewLayout(bigBinding.getRoot(),layoutParams);
            }
            return true;
        });
        bigBinding.bigBottomTv.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction()==MotionEvent.ACTION_DOWN){
                firstX=motionEvent.getRawX();
                firstY=motionEvent.getRawY();
                lpX=layoutParams.x;
                lpY=layoutParams.y;
            }else if (motionEvent.getAction()==MotionEvent.ACTION_MOVE){
                layoutParams.x= (int) (lpX+(motionEvent.getRawX()-firstX));
                layoutParams.y= (int) (lpY+(motionEvent.getRawY()-firstY));
                windowManager.updateViewLayout(bigBinding.getRoot(),layoutParams);
            }
            return true;
        });
        bigBinding.openService.setOnClickListener(view -> {
            startActivityForResult(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS),3);
            windowManager.removeView(bigBinding.getRoot());
            setFloatPara(1);
            windowManager.addView(smallBinding.getRoot(),layoutParams);
            Toast.makeText(this, "： 请选择"+getString(R.string.app_name)+"并开启", Toast.LENGTH_SHORT).show();
        });
        bigBinding.bigSwitch.setOnClickListener(view -> {
            if (MyAccessibility.mService!=null){
                MyAccessibility.mService.switchAnswer();
            }
        });
        bigBinding.bigChoose.setOnClickListener(view -> {
            windowManager.removeView(bigBinding.getRoot());
            setFloatPara(2);
            windowManager.addView(floatAnswers.getRoot(),layoutParams);
            answerdata.clear();
            answerdata.addAll(MyAccessibility.answers);
            answeradp.notifyDataSetChanged();
        });
        bigBinding.bigSubmit.setOnClickListener(view -> {
            if (MyAccessibility.mService!=null){
                MyAccessibility.mService.submit();
            }
        });
        bigBinding.bigPass.setOnClickListener(view -> {
            if (MyAccessibility.mService!=null){
                MyAccessibility.mService.pass();
            }
        });
        bigBinding.bigChooseEngine.setOnClickListener(view -> {
            windowManager.removeView(bigBinding.getRoot());
            windowManager.addView(queryBinding.getRoot(),layoutParams);
        });
    }
    private void initListener() {
        binding.open.setOnClickListener(view -> {
            if (!Settings.canDrawOverlays(this)) {
                Toast.makeText(MainActivity.this, "当前无权限，请授权", Toast.LENGTH_SHORT).show();
                startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
            }else {
                showFloatingWindow();
                startActivity(new Intent(Intent.ACTION_MAIN).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).addCategory(Intent.CATEGORY_HOME));
            }
        });
        binding.count.setOnClickListener(view -> {
            AlertDialog.Builder dialog=new AlertDialog.Builder(MainActivity.this);
            @NonNull DialogInputBinding dialogBinding = DialogInputBinding.inflate(LayoutInflater.from(MainActivity.this));
            dialog.setTitle("请输入字数范围").setView(dialogBinding.getRoot()).setPositiveButton("确定", (dialogInterface, i) -> {
                if (MyAccessibility.mService!=null){
                    @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
                    edit.putString("min",dialogBinding.dialogMin.getText().toString());
                    edit.putString("max",dialogBinding.dialogMax.getText().toString());
                    edit.apply();
                }
            }).setNeutralButton("取消",null).show();
        });
    }
    private void initLayout() {
        bigBinding=FloatBigBinding.inflate(getLayoutInflater());
        smallBinding= FloatSmallBinding.inflate(getLayoutInflater());
        floatAnswers= FloatAnswersBinding.inflate(getLayoutInflater());
        queryBinding= FloatQueryBinding.inflate(getLayoutInflater());
        layoutParams = new WindowManager.LayoutParams();
    }
    private void showFloatingWindow() {
        if (Settings.canDrawOverlays(this)) {
            windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
            setFloatPara(0);
            bigBinding.openService.setChecked(MyAccessibility.isStart());
            windowManager.addView(bigBinding.getRoot(), layoutParams);
        }
        finish();
    }
    public void setFloatPara(int type){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.flags=WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.gravity= Gravity.START|Gravity.TOP;
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(outMetrics);
        if (type==0){
            layoutParams.width=outMetrics.widthPixels/2;
            layoutParams.height=outMetrics.heightPixels/3;
        }else if (type==1){
            layoutParams.width=outMetrics.widthPixels/6;
            layoutParams.height=outMetrics.widthPixels/6;
        }else if (type==2){
            layoutParams.width=outMetrics.widthPixels;
            layoutParams.height=outMetrics.widthPixels;
        }
    }
}